/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.wms.web;

import java.io.File;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.tagext.PageData;
import javax.validation.ConstraintViolationException;

import com.google.gson.Gson;
import com.jeeplus.modules.infor.entity.*;
import com.jeeplus.modules.infor.mapper.ReAddressMapper;
import com.jeeplus.modules.infor.service.GoodsService;
import com.jeeplus.modules.infor.service.LocationService;
import com.jeeplus.modules.infor.service.ProjectService;
import com.jeeplus.modules.infor.service.UpCustomersService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.tms.entity.*;
import com.jeeplus.modules.tms.mapper.MaterialInformationsMapper;
import com.jeeplus.modules.tms.mapper.TmsMaterialsInformationMapper;
import com.jeeplus.modules.tms.service.*;
import com.jeeplus.modules.tms.util.FileUtil;
import com.jeeplus.modules.wms.entity.*;
import com.jeeplus.modules.wms.mapper.OutStatisticsMapper;
import com.jeeplus.modules.wms.mapper.StorehouseMapper;
import com.jeeplus.modules.wms.service.*;
import com.jeeplus.modules.wms.util.CopyUtil;
import com.jeeplus.modules.wms.util.ExportU;
import com.jeeplus.modules.wms.util.PrintOrder;
import org.apache.poi.hssf.usermodel.*;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;

/**
 * 出库单Controller
 * @author 李超辉
 * @version 2017-12-12
 */
@Controller
@RequestMapping(value = "${adminPath}/wms/outbound")
public class OutboundController extends BaseController {

	@Autowired
	private OutboundService outboundService;
	@Autowired
	private InventoryService inventoryService;
	@Autowired
	private StorehouseMapper mapper;
	@Autowired
	private GoodsService goodsService;
	@Autowired
	private StorageInformService storageInformService;
	@Autowired
	private MaterialParticularsService materialParticularsService;
	@Autowired
	private PickDetailedService pickDetailedService;
	@Autowired
	private TmsWaybillService tmsWaybillService;
	@Autowired
	private StorehouseMapper storehouseMapper;
	@Autowired
	private TmsMaterialsInformationMapper materialsInformationMapper;
	@Autowired
	private TransportPlanningService transportPlanningService;
	@Autowired
	private MaterialInformationsMapper mapper1;
	@Autowired
	private LocationService locationService;
	@Autowired
	private ProjectService projectService;
	@Autowired
	private OutStatisticsMapper outStatisticsMapper;
	@Autowired
	private ReAddressMapper reAddressMapper;
	@Autowired
	private JdbcTemplate jdbc;
	@Autowired
	private UpCustomersService upCustomersService;
	@Autowired
	private DispatchingService dispatchingService;
	@Autowired
	private NewBillService newBillService;
	@Autowired
	private NewTransportService newTransportService;

	@ModelAttribute
	public Outbound get(@RequestParam(required=false) String id) {
		Outbound entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = outboundService.get(id);
		}
		if (entity == null){
			entity = new Outbound();
		}
		return entity;
	}

	/**
	 * 出库单列表页面
	 */
	@RequiresPermissions("wms:outbound:list")
	@RequestMapping(value = {"list", ""})
	public String list() {
		return "modules/wms/outboundList";
	}

	/**
	 * 拣货出库页面
	 */
	@RequiresPermissions("wms:outbound:list")
	@RequestMapping(value = {"list1"})
	public String list1() {
		return "modules/wms/1/outboundList";
	}

	@RequiresPermissions("wms:outbound:list")
	@RequestMapping(value = {"list2"})
	public String list2() {
		return "modules/wms/4/outboundList";
	}

	@RequiresPermissions("wms:outbound:list")
	@RequestMapping(value = {"list3"})
	public String list3() {
		return "modules/wms/3/outboundList";
	}
	@RequiresPermissions("wms:outbound:list")
	@RequestMapping(value = {"list4"})
	public String list4() {
		return "modules/wms/6/outboundList";
	}

		/**
	 * 出库单列表数据
	 */
	@ResponseBody
	@RequiresPermissions("wms:outbound:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(Outbound outbound, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro=UserUtils.getUseroffice();
		if(!pro.equals("总部")){outbound.setProjectName(pro);}
		outbound.setFc(0);
		Page<Outbound> page = outboundService.findPage(new Page<Outbound>(request, response), outbound);
		return getBootstrapData(page);
	}
	/**
	 * 出库单列表数据
	 */
	@ResponseBody
	@RequiresPermissions("wms:outbound:list")
	@RequestMapping(value = "data1")
	public Map<String, Object> data1(Outbound outbound, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro=UserUtils.getUseroffice();
		if(!pro.equals("总部")){outbound.setProjectName(pro);}
		Page<Outbound> page;
		if(outbound.getStatus()==null||outbound.getStatus().equals("")){
			outbound.setStatus("部分");
			page = outboundService.findPage(new Page<Outbound>(request, response), outbound);
			outbound.setStatus("完成");
			Page<Outbound> page1 = outboundService.findPage(new Page<Outbound>(request, response), outbound);
			List<Outbound> list=page.getList();
			list.addAll(page1.getList());
			page.setList(list);
		}else{
			page = outboundService.findPage(new Page<Outbound>(request, response), outbound);
		}

		return getBootstrapData(page);
	}
	@ResponseBody
	@RequiresPermissions("wms:outbound:list")
	@RequestMapping(value = "data3")
	public Map<String, Object> data3(Outbound outbound, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro=UserUtils.getUseroffice();
		if(!pro.equals("总部")){outbound.setProjectName(pro);}
		outbound.setFc(1);
		Page<Outbound> page1 = outboundService.findPage(new Page<Outbound>(request, response), outbound);
		return getBootstrapData(page1);
	}
	@ResponseBody
	@RequiresPermissions("wms:outbound:list")
	@RequestMapping(value = "data4")
	public Map<String, Object> data4(Outbound outbound, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro=UserUtils.getUseroffice();
		if(!pro.equals("总部")){outbound.setProjectName(pro);}
		outbound.setStatus("完成");
		Page<Outbound> page1 = outboundService.findPage(new Page<Outbound>(request, response), outbound);
		outbound.setStatus("发车");
		Page<Outbound> page = outboundService.findPage(new Page<Outbound>(request, response), outbound);
		List<Outbound> list=page.getList();
		list.addAll(page1.getList());
		page.setList(list);
		return getBootstrapData(page);
	}
	/**
	 * 查看，增加，编辑出库单表单页面
	 */
	@RequiresPermissions(value={"wms:outbound:view","wms:outbound:add","wms:outbound:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(Outbound outbound, Model model) {
		if(outbound.getIsNewRecord()){
			String pro=UserUtils.getUseroffice();
			if(!pro.equals("总部")){outbound.setProjectName(pro);}
			outbound.setStatus("已创建");
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			String code=UserUtils.getUserAre()+sdf.format(new Date());
			Outbound o=new Outbound();
			o.setCode(code);
			List<Outbound> l=outboundService.findList(o);
			if(l==null||l.size()<1){
				outbound.setCode(code+"001"+"CK");
			}else{
				if(l.size()/10==0){
					outbound.setCode(code+"00"+(l.size()+1)+"CK");
				}else
				if(l.size()/100==0){
					outbound.setCode(code+"0"+(l.size()+1)+"CK");
				}else{outbound.setCode(code+(l.size()+1)+"CK");}

			}

			outbound.setDate(new Date());
			outbound.setOwnerCode("CC");
		}
		model.addAttribute("outbound", outbound);
		return "modules/wms/outboundForm";
	}

	/**
	 * 拣货出库
	 */
	@RequiresPermissions(value={"wms:outbound:view","wms:outbound:add","wms:outbound:edit"},logical=Logical.OR)
	@RequestMapping(value = "form1")
	public String form1(Outbound outbound, Model model) {
		model.addAttribute("outbound", outbound);
		return "modules/wms/1/outboundForm";
	}
	/**
	 * 拣货出库
	 */
	@RequestMapping(value = "form2")
	public String form2(Outbound outbound, Model model) {
		model.addAttribute("outbound", outbound);
		return "modules/wms/6/outboundForm";
	}
	/**
	 * 拣货出库
	 */
	@RequestMapping(value = "form3")
	public String form3(Outbound outbound, Model model) {
		model.addAttribute("outbound", outbound);
		return "modules/wms/7/outboundForm";
	}

	/**
	 * 保存出库单
	 */
	@ResponseBody
	@RequiresPermissions(value={"wms:outbound:add","wms:outbound:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(Outbound outbound, Model model, RedirectAttributes redirectAttributes) throws Exception{
		AjaxJson j = new AjaxJson();
		if (!beanValidator(model, outbound)){
			j.setSuccess(false);
			j.setMsg("非法参数！");
			return j;
		}
		if(outbound.getShipmentNumbers().length()<1||outbound.getDriverPhone().length()<1||outbound.getSite().length()<1||outbound.getPlateNumber().length()<1){
			j.setSuccess(false);
			j.setMsg("请检查确定无误后保存！");
			return j;
		}
		for(Storehouse s:outbound.getStorehouseList()){
			if(s.getCode().length()<1||s.getNumber().length()<1||s.getOrderNumber().length()<1){
				j.setSuccess(false);
				j.setMsg("请检查确定无误后保存！");
				return j;
			}
		}
		String pro=outbound.getUnitName();
		Project p=projectService.findUniqueByProperty("name",pro);
		if(outbound.getType().contains("调拨")&&p==null){
			j.setMsg("请检查收货地址！");
			j.setSuccess(false);
			return  j;
		}
		//新增或编辑表单保存
		int s1=0;//总订购量
		double s3=0;//总毛重
		double s4=0;//总体积
		double s5=0;//总净重
		double dg=0.0;
		double dx=0.0;
		double xx=0.0;
		double xht=0.0;
		double xt=0.0;
		double zt=0.0;
		double dt=0.0;
		double jian=0.0;
		double dai=0.0;
		List<Storehouse> l=outbound.getStorehouseList();
		String num="";
		for(Storehouse storehouse:l) {
			if(!num.contains(storehouse.getNumber())){num+=storehouse.getNumber()+",";}
			Goods goods = goodsService.get(storehouse.getName().getId());

			if (outbound.getId() != null && outbound.getId() != ""){
				String typ=storehouse.getPacking();
				if(typ.equals("吨罐")){
					dg+=Double.parseDouble(storehouse.getOrderNumber())* Double.parseDouble(goods.getGrossWeight());
				}
				if(typ.equals("吨箱")){
					dx+=Double.parseDouble(storehouse.getOrderNumber())* Double.parseDouble(goods.getGrossWeight());
				}
				if(typ.equals("小箱")){
					xx+=Double.parseDouble(storehouse.getOrderNumber())* Double.parseDouble(goods.getGrossWeight());
				}
				if(typ.equals("小黄桶")){
					xht+=Double.parseDouble(storehouse.getOrderNumber())* Double.parseDouble(goods.getGrossWeight());
				}
				if(typ.equals("小桶")){
					xt+=Double.parseDouble(storehouse.getOrderNumber())* Double.parseDouble(goods.getGrossWeight());
				}
				if(typ.equals("中桶")){
					zt+=Double.parseDouble(storehouse.getOrderNumber())* Double.parseDouble(goods.getGrossWeight());
				}
				if(typ.equals("大桶")){
					dt+=Double.parseDouble(storehouse.getOrderNumber())* Double.parseDouble(goods.getGrossWeight());
				}
				if(typ.equals("件")){
					jian+=Double.parseDouble(storehouse.getOrderNumber())* Double.parseDouble(goods.getGrossWeight());
				}
				if(typ.equals("袋")){
					dai+=Double.parseDouble(storehouse.getOrderNumber())* Double.parseDouble(goods.getGrossWeight());
				}
				s1 += Integer.parseInt(storehouse.getOrderNumber());
				s3 += Integer.parseInt(storehouse.getOrderNumber()) * Double.parseDouble(goods.getGrossWeight());
				s4 += Double.parseDouble(storehouse.getOrderNumber()) * Double.parseDouble(goods.getVolume());
				s5 += Integer.parseInt(storehouse.getOrderNumber()) * Double.parseDouble(goods.getWeight());
			}
		}
		NumberFormat nf = NumberFormat.getInstance();
		outbound.setAmount(s1 + "");
		outbound.setGrossWeight(nf.format(s3).replaceAll(",",""));
		outbound.setVolume(nf.format(s4));
		outbound.setNetWeight(nf.format(s5));
		outbound.setErpOrder(num);
		if(l!=null&&l.size()>0){
			boolean b=false;
			boolean bol=false;
			boolean bo=false;
			for(Storehouse s:l){
				if(s.getStatus()==null || s.getStatus()==""){
					s.setStatus("未拣货");
				}
				if(s.getStatus().contains("未")){
					b=true;
				}else if(s.getStatus().contains("部分")){
                     bol=true;
				}else{
					bo=true;
				}
			}
			if(!b&&!bol&&bo){
				outbound.setStatus("拣货完成");
				outbound.setDg(nf.format(dg).replaceAll(",",""));
				outbound.setDx(nf.format(dx).replaceAll(",",""));
				outbound.setXx(nf.format(xx).replaceAll(",",""));
				outbound.setXht(nf.format(xht).replaceAll(",",""));
				outbound.setXt(nf.format(xt).replaceAll(",",""));
				outbound.setZt(nf.format(zt).replaceAll(",",""));
				outbound.setDt(nf.format(dt).replaceAll(",",""));
				outbound.setJian(nf.format(jian).replaceAll(",",""));
				outbound.setDai(nf.format(dai).replaceAll(",",""));
			}else if(b&&!bo&&!bol){

			}else{outbound.setStatus("部分拣货");}
		}

		List<OutStatistics> li=outbound.getOutStatisticsList();
		if(li!=null&&li.size()>0){
			outbound.setDjzt("已登记");
		}
		outboundService.save(outbound);//保存

		String type="";
		for(OutStatistics s:li){
			if(type.contains(s.getPosition().getName())){
				continue;
			}else{
				type+=s.getPosition().getName()+",";
				if(s.getDg()!=null&&!"".equals(s.getDg())){
					continue;
				}else{
					double i=0;
					String  p1=s.getPosition().getId();
					for(OutStatistics s11:li){
						if(s11.getPosition().getId().equals(p1)){
							i++;
						}
					}

					for(OutStatistics s2:li){
						if(s2.getPosition().getId().equals(p1)){
							s2.setDg(Double.parseDouble(outbound.getDg())/i+"");
							s2.setDx(Double.parseDouble(outbound.getDx())/i+"");
							s2.setXht(Double.parseDouble(outbound.getXht())/i+"");
							s2.setXx(Double.parseDouble(outbound.getXx())/i+"");
							s2.setXt(Double.parseDouble(outbound.getXt())/i+"");
							s2.setZt(Double.parseDouble(outbound.getZt())/i+"");
							s2.setDt(Double.parseDouble(outbound.getDt())/i+"");
							s2.setJian(Double.parseDouble(outbound.getJian())/i+"");
							s2.setDai(Double.parseDouble(outbound.getDai())/i+"");
							outStatisticsMapper.update(s2);
						}
					}
				}
			}



		}
		j.setSuccess(true);
		j.setMsg("保存出库单成功");
		return j;
	}
	/**
	 * 保存出库单
	 */
	@ResponseBody
	@RequiresPermissions(value={"wms:outbound:add","wms:outbound:edit"},logical=Logical.OR)
	@RequestMapping(value = "save1")
	public AjaxJson save1(Outbound outbound, Model model, RedirectAttributes redirectAttributes) throws Exception{
		AjaxJson j = new AjaxJson();
		PickDetailed p=new PickDetailed();
		p.setOutbount(outbound.getId());
		List<PickDetailed> list=pickDetailedService.findList(p);
		List<Storehouse> lis=outbound.getStorehouseList();
		for(PickDetailed pi:list){
			pi.setShippingOrder(outbound.getShipmentNumbers());
			for(Storehouse s:lis){
				if(s.getCode().equals(pi.getCode())){
					pi.setNumber(s.getNumber());
				}
			}
			pickDetailedService.save(pi);
		}
         outboundService.save(outbound);
		j.setSuccess(true);
		j.setMsg("保存出库单成功");
		return j;
	}


	/**
	 * 保存出库单
	 */
	@ResponseBody
	@RequiresPermissions(value={"wms:outbound:add","wms:outbound:edit"},logical=Logical.OR)
	@RequestMapping(value = "save2")
	public AjaxJson save2(Outbound outbound, Model model, RedirectAttributes redirectAttributes){
		AjaxJson j = new AjaxJson();
			List<OutStatistics> li=outbound.getOutStatisticsList();
		if(li!=null&&li.size()>0){
			outbound.setDjzt("已登记");
		}
		outboundService.save(outbound);//保存

		String type="";
		for(OutStatistics s:li){
			if(type.contains(s.getPosition().getName())){
				continue;
			}else{
				type+=s.getPosition().getName()+",";
				if(s.getDg()!=null&&!"".equals(s.getDg())){
					continue;
				}else{
					double i=0;
					String  p1=s.getPosition().getId();
					for(OutStatistics s11:li){
						if(s11.getPosition().getId().equals(p1)){
							i++;
						}
					}

					for(OutStatistics s2:li){
						if(s2.getPosition().getId().equals(p1)){
							s2.setDg(Double.parseDouble(outbound.getDg())/i+"");
							s2.setDx(Double.parseDouble(outbound.getDx())/i+"");
							s2.setXht(Double.parseDouble(outbound.getXht())/i+"");
							s2.setXx(Double.parseDouble(outbound.getXx())/i+"");
							s2.setXt(Double.parseDouble(outbound.getXt())/i+"");
							s2.setZt(Double.parseDouble(outbound.getZt())/i+"");
							s2.setDt(Double.parseDouble(outbound.getDt())/i+"");
							s2.setJian(Double.parseDouble(outbound.getJian())/i+"");
							s2.setDai(Double.parseDouble(outbound.getDai())/i+"");
							outStatisticsMapper.update(s2);
						}
					}
				}
			}



		}
		j.setSuccess(true);
		j.setMsg("保存出库单成功");
		return j;
	}
	/**
	 * 删除出库单
	 */
	@ResponseBody
	@RequiresPermissions("wms:outbound:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(Outbound outbound, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		outboundService.delete(outbound);
		j.setMsg("删除出库单成功");
		return j;
	}

	/**
	 * 导出日统计
	 */
	@ResponseBody
	@RequestMapping(value = "daochu0")
	public void daochu0(HttpServletResponse response) {
		//获取数据
		List<Map<String,Object>> list=day();
		SimpleDateFormat sdf =   new SimpleDateFormat( "yyyy年MM月dd日" );
		String str = sdf.format(new Date());
		ExportU e=new ExportU();
		e.export(response,str,list);
	}
	/**
	 * 导出月统计
	 */
	@ResponseBody
	@RequestMapping(value = "daochu")
	public void daochu(HttpServletResponse response) {
		//获取数据
		List<Map<String,Object>> list=yue();
		SimpleDateFormat sdf =   new SimpleDateFormat( "yyyy年MM月" );
		String str = sdf.format(new Date());
		ExportU e=new ExportU();
		e.export(response,str,list);
	}
	/**
	 * 导出季度统计
	 */
	@ResponseBody
	@RequestMapping(value = "daochu1")
	public void daochu1(HttpServletResponse response) {
		//获取数据
		List<Map<String,Object>> list=jidu();
		SimpleDateFormat sdf =   new SimpleDateFormat( "yyyy年" );
		String str = sdf.format(new Date())+"第"+(new Date().getMonth()%3+1)+"季度";
		ExportU e=new ExportU();
		e.export(response,str,list);
	}


	/**
	 * 导出年统计
	 */
	@ResponseBody
	@RequestMapping(value = "daochu2")
	public void daochu2(HttpServletResponse response) {
		//获取数据
		List<Map<String,Object>> list=year();
		SimpleDateFormat sdf =   new SimpleDateFormat( "yyyy年度" );
		String str = sdf.format(new Date());
		ExportU e=new ExportU();
		e.export(response,str,list);
	}

	/**
	 * 批量删除出库单
	 */
	@ResponseBody
	@RequiresPermissions("wms:outbound:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			Outbound o=outboundService.get(id);
			TmsWaybill t=tmsWaybillService.findUniqueByProperty("code",o.getExternalOrder());
			if(t!=null){
				t.setBillStatus("已配载");
				tmsWaybillService.save(t);
			}

			outboundService.delete(o);
		}
		j.setMsg("删除出库单成功");
		return j;
	}

	/**
	 * 发车(新)
	 */
	@ResponseBody
	@RequiresPermissions("wms:outbound:edit")
	@RequestMapping(value = "update1")
	public AjaxJson update1(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String[] id=ids.split(",");
		for(String idss:id){
			Outbound o=outboundService.get(idss);
		List<Storehouse> list=o.getStorehouseList();
		o.setStatus("已发车");
		o.setFc(1);

		for(Storehouse s:list){
			String bil=s.getBill();
            if(bil!=null&&bil!=""){
            	NewBill nb=newBillService.get(bil);
            	nb.setZcl(s.getPicking());
            	nb.setStatus("已出库");
				newBillService.save(nb);			}
		}
			outboundService.save(o);
		String pcd=o.getPcd();
		if(pcd!=""&&pcd!=null){
			Dispatching d=dispatchingService.get(pcd);
			Outbound oub=new Outbound();
			oub.setPcd(pcd);
			List<Outbound> os=outboundService.findList(oub);
			boolean bol=true;
			for(Outbound b:os){
				if(b.getFc()!=1){
					bol=false;
				}
			}
			if(bol){
				d.setStatus("已出库");
			}else{
				d.setStatus("部分出库");
			}
			dispatchingService.save(d);
		}


			}
		j.setMsg("发车成功");
		return j;
	}

	/**
	 * 发车
	 */
	@ResponseBody
	@RequiresPermissions("wms:outbound:edit")
	@RequestMapping(value = "update")
	public AjaxJson update(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String[] id=ids.split(",");
		for(String idss:id){
			Outbound o=outboundService.get(idss);
			List<Storehouse> list=o.getStorehouseList();
			o.setStatus("已发车");
			o.setFc(1);
			outboundService.save(o);
			if(o.getType().equals("调拨出库")){
				String pro=o.getUnitName();
				Project project=projectService.findUniqueByProperty("name",pro);
				StorageInform s=new StorageInform();
				s.setProjectName(pro);
				s.setState("已创建");
				s.setDeliveryNumber(o.getErpOrder());
				s.setShippingNumber(o.getShipmentNumbers());
				SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
				String code=project.getRemarks()+sdf.format(new Date());
				StorageInform s0=new StorageInform();
				s0.setStorageNumber(code);
				List<StorageInform> l=storageInformService.findList(s0);
				if(l==null||l.size()<1){
					s.setStorageNumber(code+"001"+"RK");
				}else{
					if(l.size()/10==0){
						s.setStorageNumber(code+"00"+(l.size()+1)+"RK");
					}else
					if(l.size()/100==0){
						s.setStorageNumber(code+"0"+(l.size()+1)+"RK");
					}else{s.setStorageNumber(code+(l.size()+1)+"RK");}

				}
				s.setShipperCode("CC");
				s.setStorageType("调拨入库");
				//s.setExpectDate(o.getArrivalTime());
				//s.setArrivalDate(o.getArrivalTime());
				s.setRoughWeight(o.getGrossWeight());
				s.setTotalVolume(o.getVolume());
				s.setProviderName(o.getLogisticsName());
				s.setName(o.getLogisticsPerson());
				s.setPhone(o.getLogisticsPhone());
				s.setForecast(o.getAmount());
				s.setNumber(o.getPlateNumber());
				s.setDriverPhone(o.getDriverPhone());
				s.setTransportationWay(o.getTransportMode());
				s.setDriverName(o.getDriverName());
				s.setOwnerName(o.getOwnerName());
				s.setSite(o.getOwnerAddress());
				s.setLogisticsBumber(o.getLogisticsOrder());
				s.setSystemName(o.getProjectName());
				storageInformService.save(s);
				List<Storehouse>  list0=o.getStorehouseList();
				NumberFormat nf = NumberFormat.getInstance();
				for(Storehouse s1:list0){
					MaterialParticulars v=new MaterialParticulars();
					v.setMaterialCode(s1.getCode());
					v.setQuantitiesReceived("0");
					v.setMaterialName(s1.getName());
					Goods g=goodsService.get(s1.getName().getId());
					v.setState("未入库");
					v.setForecast(s1.getPicking());
					v.setMaterialSpecification(g.getSpecifications());

					v.setGoodsNumber(s1.getNumber());
					int num=Integer.parseInt(s1.getPicking());
					v.setWeight(nf.format(Double.parseDouble(g.getWeight())*num));
					v.setRoughWeight(nf.format(Double.parseDouble(g.getGrossWeight())*num));
					v.setVolume(nf.format(Double.parseDouble(g.getVolume())*num));
					v.setPacking(g.getType().getName());
					v.setPackingUnit(g.getPacking());
					v.setStorageInform(s);
					materialParticularsService.save(v);
				}




			}
			TmsWaybill t=tmsWaybillService.findUniqueByProperty("code",o.getExternalOrder());
			if(t!=null){
				t=tmsWaybillService.get(t.getId());
				List<TmsMaterialsInformation> l=t.getTmsMaterialsInformationList();
				for(Storehouse s:list){
					for(TmsMaterialsInformation m:l){
						if(m.getNumber().equals(s.getNumber())){
							m.setLoadingQuantity(s.getPicking());
							materialsInformationMapper.update(m);
						}
					}

				}
				t.setBillStatus("已出库");
				tmsWaybillService.save(t);
			}}
		j.setMsg("发车成功");
		return j;
	}

	@ResponseBody
	@RequestMapping("qxck")
	public  String qxck(String ids){
		Outbound o=outboundService.get(ids);
		o.setStatus("已创建");
		outboundService.save(o);
		List<Storehouse> list=o.getStorehouseList();
		for(Storehouse s:list){
			s.setStatus("未拣货");
			s.setPicking("0");
			storehouseMapper.update(s);
		}
		PickDetailed p=new PickDetailed();
		p.setOutbount(ids);
		List<PickDetailed> li=pickDetailedService.findList(p);
		for(PickDetailed pick:li){
			Inventory inventory=new Inventory();
			inventory.setCode(pick.getCode());
			Goods g=new Goods();
			g.setCode(inventory.getCode());
			g.setProject(UserUtils.getUseroffice());
			g=goodsService.findList(g).get(0);
			inventory.setName(g);
			Location l=new Location();
			l.setName(pick.getLocation());
			l.setProjectName(UserUtils.getUseroffice());
			l=locationService.findList(l).get(0);
			inventory.setLocation(l);
			inventory.setBatch(pick.getBach());
			List<Inventory> lis=inventoryService.findList(inventory);
			if(lis!=null&&lis.size()>0){
				Inventory inv=lis.get(0);
				String f=inv.getUsable();
				String e=inv.getInventoryNumber();
				inv.setUsable((Integer.parseInt(f)+Integer.parseInt(pick.getAmount()))+"");
				inv.setInventoryNumber((Integer.parseInt(e)+Integer.parseInt(pick.getAmount()))+"");
				inventoryService.save(inv);
			}else{
				inventory.setProjectName(UserUtils.getUseroffice());
				inventory.setShipperCode("CC");
				inventory.setUsable(pick.getAmount());
				inventory.setAllocation("0");
				inventory.setPicking("0");
				inventory.setLsPicking("0");
				inventory.setInventoryNumber(pick.getAmount());
				inventoryService.save(inventory);
			}
			pickDetailedService.delete(pick);
		}
		return "";
	}

	/**
	 * 拆单（新）
	 */
	@ResponseBody
	@RequiresPermissions("wms:outbound:edit")
	@RequestMapping(value = "cd1")
	public AjaxJson cd1(String ids, Model model,  RedirectAttributes redirectAttributes) throws Exception {
		AjaxJson j = new AjaxJson();
		Outbound o=outboundService.get(ids);
		List<Storehouse> list=o.getStorehouseList();
		o.setStatus("拣货完成");
		NumberFormat nf = NumberFormat.getInstance();
		String pcd=o.getPcd();
		Dispatching d=new Dispatching();
		if(pcd!=null&&pcd!=""){
			 d=dispatchingService.get(pcd);
		}

		//TmsWaybill bill=tmsWaybillService.findUniqueByProperty("code",o.getExternalOrder());
//		Outbound od=new Outbound();
//		od= (Outbound) CopyUtil.Copy(od,o,false);
//		od.setCode(od.getCode()+"-01");
//		od.setStatus("已创建");
		//List<Storehouse> ss=new ArrayList<>();
		for(int i=0;i<list.size();i++){
			Storehouse sh=list.get(i);
			String status=sh.getStatus();
			String num=sh.getPicking();
			String n=sh.getOrderNumber();
			Goods g=goodsService.get(sh.getName().getId());
//			g.setCode(list.get(i).getCode());
//			g.setProject(UserUtils.getUseroffice());
//			g=goodsService.findList(g).get(0);
			String bil=sh.getBill();
			if(status.contains("部分")){
				if(bil!=null&bil!=""){
					NewBill bill=newBillService.get(bil);
					NewTransport nt=newTransportService.get(bill.getPort());
					bill.setZcl(list.get(i).getPicking());
					bill.setWeight(nf.format(Double.parseDouble(g.getGrossWeight())*Integer.parseInt(sh.getPicking())));
					bill.setVoulm(nf.format(Double.parseDouble(g.getVolume())*Integer.parseInt(sh.getPicking())));
					newBillService.save(bill);
					String pcl=nt.getPcl();
					String gr=nt.getGross();
					int zz=Integer.parseInt(pcl)-(Integer.parseInt(n)-Integer.parseInt(num));
					int wf=Integer.parseInt(gr)-zz;
					nt.setPcl(zz+"");
					nt.setWf(nf.format(wf*Double.parseDouble(g.getGrossWeight())).replaceAll(",",""));
					nt.setYf(nf.format(zz*Double.parseDouble(g.getGrossWeight())).replaceAll(",",""));
					nt.setJhstatus("部分计划");
					newTransportService.save(nt);


				}
				list.get(i).setOrderNumber(sh.getPicking());
				list.get(i).setStatus("拣货完成");
				storehouseMapper.update(list.get(i));

			}
			if(status.contains("未")){
				if(bil!=null&bil!=""){
					String bills=d.getRemarks();
					String[] nm=bills.split(",");
					String nb="";
					for(String tr:nm){
						if(!tr.equals(bil)){
							nb+=tr+",";
						}
					}
					d.setRemarks(nb);
					dispatchingService.save(d);
					NewBill bill=newBillService.get(bil);
					NewTransport nt=newTransportService.get(bill.getPort());
					newBillService.delete(bill);
					String pcl=nt.getPcl();
					String gr=nt.getGross();
					int zz=Integer.parseInt(pcl)-Integer.parseInt(n);
					int wf=Integer.parseInt(gr)-zz;
					nt.setPcl(zz+"");
					nt.setWf(nf.format(wf*Double.parseDouble(g.getGrossWeight())).replaceAll(",",""));
					nt.setYf(nf.format(zz*Double.parseDouble(g.getGrossWeight())).replaceAll(",",""));
					if(zz==0){
						nt.setJhstatus("未计划");
					}else{
						nt.setJhstatus("部分计划");
					}
					newTransportService.save(nt);
				}
				storehouseMapper.delete(list.get(i));
			}
			if(status.contains("完成")){
				if(bil!=null&bil!=""){
					NewBill bill=newBillService.get(bil);
					NewTransport nt=newTransportService.get(bill.getPort());
					bill.setZcl(bill.getPcl());
					newBillService.save(bill);
				}


			}
		}


		o=cz(o);
		outboundService.save(o);
		j.setMsg("拆单成功");
		return j;
	}
	/**
	 * 拆单
	 */
	@ResponseBody
	@RequiresPermissions("wms:outbound:edit")
	@RequestMapping(value = "cd")
	public AjaxJson cd(String ids, Model model,  RedirectAttributes redirectAttributes) throws Exception {
		AjaxJson j = new AjaxJson();
          Outbound o=outboundService.get(ids);
		  List<Storehouse> list=o.getStorehouseList();
		  o.setStatus("拣货完成");
		NumberFormat nf = NumberFormat.getInstance();
		  TmsWaybill bill=tmsWaybillService.findUniqueByProperty("code",o.getExternalOrder());
		Outbound od=new Outbound();
		od= (Outbound) CopyUtil.Copy(od,o,false);
		od.setCode(od.getCode()+"-01");
		od.setStatus("已创建");
		  List<Storehouse> ss=new ArrayList<>();
		      for(int i=0;i<list.size();i++){
		    	String status=list.get(i).getStatus();
				String num=list.get(i).getPicking();
				String n=list.get(i).getOrderNumber();
				Goods g=new Goods();
				g.setCode(list.get(i).getCode());
				g.setProject(UserUtils.getUseroffice());
				g=goodsService.findList(g).get(0);
		  	if(status.contains("部分")){
				if(bill!=null){
					bill=tmsWaybillService.get(bill.getId());
					List<TmsMaterialsInformation> l=bill.getTmsMaterialsInformationList();
					TransportPlanning t=transportPlanningService.findUniqueByProperty("pid",bill.getPid());
					t=transportPlanningService.get(t.getId());
					List<MaterialInformations> li=t.getMaterialInformationsList();
		  		for(TmsMaterialsInformation tm:l){
		  			if(tm.getCoding().equals(list.get(i).getCode())&&tm.getNumber().equals(list.get(i).getNumber())){
						tm.setLoadingQuantity(list.get(i).getPicking());
						tm.setWeight(nf.format(Double.parseDouble(g.getGrossWeight())*Integer.parseInt(list.get(i).getPicking())));
						tm.setVolume(nf.format(Double.parseDouble(g.getVolume())*Integer.parseInt(list.get(i).getPicking())));
						materialsInformationMapper.update(tm);
					}
				}
                for(MaterialInformations m:li){
		  			if(m.getCoding().equals(list.get(i).getCode())&&m.getNumber().equals(list.get(i).getNumber())){
		  				int cy=Integer.parseInt(n)-Integer.parseInt(num);
                        t.setWf(t.getWf()+(cy*Double.parseDouble(g.getGrossWeight())));
                        t.setWf(Double.parseDouble(nf.format(t.getWf())));
						m.setRemain((Integer.parseInt(m.getRemain())+Integer.parseInt(n)-Integer.parseInt(num))+"");
						m.setVehicleQuantity((Integer.parseInt(m.getVehicleQuantity())+Integer.parseInt(num)-Integer.parseInt(n))+"");
						mapper1.update(m);
					}
				}
					transportPlanningService.save(t);
				}else{
					Storehouse s=new Storehouse();
					s= (Storehouse) CopyUtil.Copy(s,list.get(i),false);
					s.setOrderNumber((Integer.parseInt(n)-Integer.parseInt(num))+"");
					s.setPicking("0");
					s.setStatus("未拣货");
					ss.add(s);

				}
				list.get(i).setOrderNumber(list.get(i).getPicking());
				list.get(i).setStatus("拣货完成");
				storehouseMapper.update(list.get(i));

			}
			  if(status.contains("未")){
				  if(bill!=null){
					  bill=tmsWaybillService.get(bill.getId());
					  List<TmsMaterialsInformation> l=bill.getTmsMaterialsInformationList();
					  TransportPlanning t=transportPlanningService.findUniqueByProperty("entrust_number",bill.getEntrustNumber());
					  t=transportPlanningService.get(t.getId());
					  List<MaterialInformations> li=t.getMaterialInformationsList();
				  for(TmsMaterialsInformation tm:l){
					  if(tm.getCoding().equals(list.get(i).getCode())&&tm.getNumber().equals(list.get(i).getNumber())){
						  tm.setLoadingQuantity("0");
						  tm.setVolume("0");
						  tm.setWeight("0");
						  materialsInformationMapper.update(tm);
					  }
				  }
				  for(MaterialInformations m:li){
					  if(m.getCoding().equals(list.get(i).getCode())&&m.getNumber().equals(list.get(i).getNumber())){
						  int cy=Integer.parseInt(n);
						  t.setWf(t.getWf()+(cy*Double.parseDouble(g.getGrossWeight())));
						  t.setWf(Double.parseDouble(nf.format(t.getWf())));
						  m.setRemain((Integer.parseInt(m.getRemain())+Integer.parseInt(n))+"");
						  m.setVehicleQuantity((Integer.parseInt(m.getVehicleQuantity())-Integer.parseInt(n))+"");
						  mapper1.update(m);
					  }
				  }
					  transportPlanningService.save(t);
				  }else{
                      Storehouse s=new Storehouse();
                      s= (Storehouse) CopyUtil.Copy(s,list.get(i),false);
                      ss.add(s);
				  }
				  storehouseMapper.delete(list.get(i));
			   }
			   if(status.contains("完成")){
				   if(bill!=null){
					   bill=tmsWaybillService.get(bill.getId());
					   List<TmsMaterialsInformation> l=bill.getTmsMaterialsInformationList();
					   TransportPlanning t=transportPlanningService.findUniqueByProperty("entrust_number",bill.getEntrustNumber());
					   t=transportPlanningService.get(t.getId());
					   List<MaterialInformations> li=t.getMaterialInformationsList();
				   for(TmsMaterialsInformation tm:l){
					   if(tm.getCoding().equals(list.get(i).getCode())&&tm.getNumber().equals(list.get(i).getNumber())){
						   tm.setLoadingQuantity(list.get(i).getPicking());
						   materialsInformationMapper.update(tm);
					   }
				   }
			   }}
		  }if(bill!=null){
			bill=tmsWaybillService.get(bill.getId());
			List<TmsMaterialsInformation> l=bill.getTmsMaterialsInformationList();
			TransportPlanning t=transportPlanningService.findUniqueByProperty("entrust_number",bill.getEntrustNumber());
			t=transportPlanningService.get(t.getId());
			List<MaterialInformations> li=t.getMaterialInformationsList();

        tmsWaybillService.save(bill);
		t.setPlanStatus("部分计划");
		transportPlanningService.save(t);}else{
		  	outboundService.save(od);
		  	for(Storehouse si:ss){
		  		si.setOutbound(od);
		  		si.setId(UUID.randomUUID().toString().replaceAll("-",""));
		  		storehouseMapper.insert(si);
			}
			od=cz(outboundService.get(od.getId()));
		  	outboundService.save(od);
		}

		o=cz(o);
		outboundService.save(o);
		j.setMsg("拆单成功");
		return j;
	}
 public  Outbound cz(Outbound o){
	 NumberFormat nf = NumberFormat.getInstance();
	 double dg=0.0;
	 double dx=0.0;
	 double xx=0.0;
	 double xht=0.0;
	 double xt=0.0;
	 double zt=0.0;
	 double dt=0.0;
	 int s1=0;//总订购量
	 double s3=0;//总毛重
	 double s4=0;//总体积
	 double s5=0;//总净重
	 for(Storehouse ho:o.getStorehouseList()){
		 Goods goods = goodsService.get(ho.getName().getId());

		 s1 += Integer.parseInt(ho.getOrderNumber());
		 s3 += Integer.parseInt(ho.getOrderNumber()) * Double.parseDouble(goods.getGrossWeight());
		 s4 += Double.parseDouble(ho.getOrderNumber()) * Double.parseDouble(goods.getVolume());
		 s5 += Integer.parseInt(ho.getOrderNumber()) * Double.parseDouble(goods.getWeight());
		 String typ=ho.getPacking();
		 if(typ.equals("吨罐")){
			 dg+=Double.parseDouble(ho.getOrderNumber())* Double.parseDouble(goods.getGrossWeight());
		 }
		 if(typ.equals("吨箱")){
			 dx+=Double.parseDouble(ho.getOrderNumber())* Double.parseDouble(goods.getGrossWeight());
		 }
		 if(typ.equals("小箱")){
			 xx+=Double.parseDouble(ho.getOrderNumber())* Double.parseDouble(goods.getGrossWeight());
		 }
		 if(typ.equals("小黄桶")){
			 xht+=Double.parseDouble(ho.getOrderNumber())* Double.parseDouble(goods.getGrossWeight());
		 }
		 if(typ.equals("小桶")){
			 xt+=Double.parseDouble(ho.getOrderNumber())* Double.parseDouble(goods.getGrossWeight());
		 }
		 if(typ.equals("中桶")){
			 zt+=Double.parseDouble(ho.getOrderNumber())* Double.parseDouble(goods.getGrossWeight());
		 }
		 if(typ.equals("大桶")){
			 dt+=Double.parseDouble(ho.getOrderNumber())* Double.parseDouble(goods.getGrossWeight());
		 }
	 }
	 o.setDg(nf.format(dg).replaceAll(",",""));
	 o.setDx(nf.format(dx).replaceAll(",",""));
	 o.setXx(nf.format(xx).replaceAll(",",""));
	 o.setXht(nf.format(xht).replaceAll(",",""));
	 o.setXt(nf.format(xt).replaceAll(",",""));
	 o.setZt(nf.format(zt).replaceAll(",",""));
	 o.setDt(nf.format(dt).replaceAll(",",""));
	 o.setAmount(nf.format(s1).replaceAll(",",""));
	 o.setGrossWeight(nf.format(s3).replaceAll(",",""));
	 o.setVolume(nf.format(s4).replaceAll(",",""));
	 o.setNetWeight(nf.format(s5).replaceAll(",",""));
		return o;
 }
	@RequestMapping("updatedetil")
	@ResponseBody
	public  String updatedetil(String d,int sl){
		Storehouse s=mapper.get(d);
		s.setPicking(sl+"");
		if(Integer.parseInt(s.getOrderNumber())==sl){
			s.setStatus("拣货完成");
		}else if(sl>0){
			s.setStatus("部分拣货");
		}
		mapper.update(s);
		return "";
	}
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("wms:outbound:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public AjaxJson exportFile(Outbound outbound, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "出库单"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<Outbound> page = outboundService.findPage(new Page<Outbound>(request, response, -1), outbound);
    		new ExportExcel("出库单", Outbound.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出出库单记录失败！失败信息："+e.getMessage());
		}
			return j;
    }

    @ResponseBody
    @RequestMapping(value = "detail")
	public Outbound detail(String id) {
		Outbound o= outboundService.get(id);
		return o;
	}

	@ResponseBody
	@RequestMapping(value = "wlList")
	public String wldetail(String ii) {
    Inventory i=new Inventory();
    i.setName(goodsService.get(ii));
    String pro= UserUtils.getUseroffice();
    i.setProjectName(pro);
	List<Inventory> list=inventoryService.findList1(i);
		Gson g=new Gson();
		return  g.toJson(list).toString();
	}


	public void inset(Outbound o,ImportOutbound outbound){
		Storehouse s=new Storehouse();
		s.setOutbound(o);
		List<Storehouse> li=storehouseMapper.findList(s);
		if(li!=null&&li.size()>0){
			s.setIdx(li.size());
		}else{
			s.setIdx(0);
		}
		s.setOrderNumber(outbound.getAmount());
		s.setCode(outbound.getCoding());
		Goods g=new Goods();
		g.setProject(UserUtils.getUseroffice());
		g.setCode(outbound.getCoding());
		g=goodsService.findList(g).get(0);
		g=goodsService.get(g.getId());
		s.setName(g);
		s.setUnit(g.getPacking());
		s.setPacking(g.getType().getName());
		s.setNumber(outbound.getNumber());
		s.setPro(UserUtils.getUseroffice());
		s.setStatus("未拣货");
		s.setId(UUID.randomUUID().toString().replace("-",""));
		storehouseMapper.insert(s);
	}
	/**
	 * 导入Excel数据
	 */
	@RequiresPermissions("wms:outbound:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file,Model model, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<ImportOutbound> list = ei.getDataList(ImportOutbound.class);
			for (ImportOutbound outbound : list){
				try{String zy=outbound.getShipmentNumbers();
					Outbound o=new Outbound();
					o.setShipmentNumbers(outbound.getShipmentNumbers());
					o.setProjectName(UserUtils.getUseroffice());

					List<Outbound> l=outboundService.findList(o);
					if(l!=null&&l.size()>0){
						o=l.get(0);
						inset(o,outbound);
						save(outboundService.get(o.getId()),model,redirectAttributes );
					}else {
						SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
						String code=UserUtils.getUserAre()+sdf.format(new Date());
						Outbound pi=new Outbound();
						pi.setCode(code);
						List<Outbound> li=outboundService.findList(pi);
						if(li==null||li.size()<1){
							o.setCode(code+"001"+"CK");
						}else{
							if(li.size()/10==0){
								o.setCode(code+"00"+(li.size()+1)+"CK");
							}else
							if(li.size()/100==0){
								o.setCode(code+"0"+(li.size()+1)+"CK");
							}else{o.setCode(code+(li.size()+1)+"CK");}

						}
						o.setDate(new Date());
						ReAddress r=new ReAddress();
						r.setProjectName(UserUtils.getUseroffice());
						r.setAddress(outbound.getSite());
						r=reAddressMapper.findList(r).get(0);
						r=reAddressMapper.get(r.getId());
						o.setUnitName(r.getLnCustomers().getCompany());
						o.setUnitConfirmor(r.getPerson());
						o.setPhone(r.getPhone());
						o.setLogisticsName(outbound.getWls());
						o.setDriverName(outbound.getDriverName());
						o.setDriverPhone(outbound.getPhone());
						o.setPlateNumber(outbound.getTruckNumber());
						o.setSite(outbound.getSite());
						o.setArriveCity(r.getCity());
						o.setArriveProvince(r.getProvince());
						o.setProjectName(UserUtils.getUseroffice());
						o.setDistance(r.getMileage());
						o.setTransitLines(r.getLine());
						o.setProjectName(UserUtils.getUseroffice());
						o.setStatus("已创建");
						o.setType("普通出库");
						o.setWorkType("常规");
						outboundService.save(o);
						inset(o,outbound);
						save(outboundService.get(o.getId()),model,redirectAttributes );
					}
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条出库单记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条出库单记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入出库单失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/wms/outbound/?repage";
    }

	/**
	 * 下载导入出库单数据模板
	 */
	@RequiresPermissions("wms:outbound:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "出库单数据导入模板.xlsx";
    		List<ImportOutbound> list = Lists.newArrayList();
    		new ExportExcel("出库单数据", ImportOutbound.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/wms/outbound/?repage";
    }

    public  List<Map<String ,Object>> hb(List<Map<String ,Object>> list,List<Map<String ,Object>> lis){
		NumberFormat nf = NumberFormat.getInstance();
		for(Map<String,Object> m:list){
			boolean bo=false;
			Goods goods=new Goods();
			goods.setProject(UserUtils.getUseroffice());
			goods.setCode(m.get("code").toString());
			goods=goodsService.findList(goods).get(0);
			m.put("gg",goods.getSpecifications());
			Double w=Double.parseDouble(goods.getGrossWeight());
			Double num= (Double) m.get("amount");
			m.put("pweight",nf.format(w*num));
			m.put("amount",num.toString().substring(0,num.toString().lastIndexOf(".")));
			for(Map<String,Object> map:lis){
				if(m.get("code").toString().equals(map.get("code").toString())&&m.get("type").toString().equals(map.get("type").toString())){
                     bo=true;
				}}
				if(bo){
					for(Map<String,Object> map:lis){
						if(m.get("code").toString().equals(map.get("code").toString())&&m.get("type").toString().equals(map.get("type").toString())){
							Double p= (Double) map.get("amount");
							m.put("recive",p.toString().substring(0,p.toString().lastIndexOf(".")));
							m.put("rweight",nf.format(w*p));
						}
					}
				}else{
					m.put("recive","0");
					m.put("rweight","0");
				}


		}
		List<Map<String ,Object>> list11=new ArrayList<>();
		for(Map<String,Object> m:lis){
			boolean bol=true;
			for(Map<String,Object> mm:list){
				if(m.get("code").toString().equals(mm.get("code").toString())&&m.get("type").toString().equals(mm.get("type").toString())){
					bol=false;
					break;
				}
			}
			if(bol){
				Goods goods=new Goods();
				goods.setProject(UserUtils.getUseroffice());
				goods.setCode(m.get("code").toString());
				goods=goodsService.findList(goods).get(0);
				Map<String,Object> mm=new HashMap<String, Object>() ;
				mm.put("name",goods.getName());
				mm.put("gg",goods.getSpecifications());
				mm.put("code",m.get("code"));
				mm.put("type",m.get("type"));
				mm.put("amount",0);
				mm.put("pweight",0);
				mm.put("recive",m.get("amount").toString().substring(0,m.get("amount").toString().lastIndexOf(".")));
				Double w=Double.parseDouble(goods.getGrossWeight());
				Double num= (Double) m.get("amount");
				mm.put("rweight",nf.format(w*num));
				list11.add(mm);
			}
		}
		list.addAll(list11);
		return  list;
	}
	/**
	 * 当天的统计
	 */
	public List<Map<String,Object>> day(){
		String pro=UserUtils.getUseroffice();
    	String sql="SELECT p.code as code, p.name AS name, p.unit as unit,SUM(p.amount) as amount,p.work_type as type FROM wms_pickdetailed p  where to_days(p.create_date) = to_days(now()) and p.project_name='"+pro+"' GROUP BY p.`code`,p.work_type";
		String sq="SELECT p.material_coding as code,SUM(p.quantities_received) as amount ,p.work_type as type FROM wms_receivings_notes p  where to_days(p.create_date) = to_days(now()) and p.project_name='"+pro+"' GROUP BY p.material_coding,p.work_type";
		List<Map<String,Object>> list=jdbc.queryForList(sql);
		List<Map<String,Object>> lis=jdbc.queryForList(sq);
		list=hb(list,lis);
		return list;

	}
	/**
	 * 当月的统计
	 */
	public List<Map<String,Object>> yue(){
		String pro=UserUtils.getUseroffice();
		String sql="SELECT p.code as code, p.name AS name, p.unit as unit,SUM(p.amount) as amount ,p.work_type as type FROM wms_pickdetailed p  where DATE_FORMAT( p.create_date, '%Y%m' ) = DATE_FORMAT( CURDATE( ) , '%Y%m' ) and p.project_name='"+pro+"' GROUP BY p.`code`,p.work_type";
		String sq="SELECT p.material_coding as code,SUM(p.quantities_received) as amount ,p.work_type as type FROM wms_receivings_notes p  where DATE_FORMAT( p.create_date, '%Y%m' ) = DATE_FORMAT( CURDATE( ) , '%Y%m' ) and p.project_name='"+pro+"' GROUP BY p.material_coding,p.work_type";
		List<Map<String,Object>> list=jdbc.queryForList(sql);
		List<Map<String,Object>> lis=jdbc.queryForList(sq);
		list=hb(list,lis);
		return list;

	}

	/**
	 * 本季度的统计
	 */
	public List<Map<String,Object>> jidu(){
		String pro=UserUtils.getUseroffice();
		String sql="SELECT p.code as code, p.name AS name, p.unit as unit,SUM(p.amount) as amount ,p.work_type as type FROM wms_pickdetailed p  where QUARTER(p.create_date)=QUARTER(now()) and p.project_name='"+pro+"' GROUP BY p.`code`,p.work_type";
		String sq="SELECT p.material_coding as code,SUM(p.quantities_received) as amount ,p.work_type as type FROM wms_receivings_notes p  where QUARTER(p.create_date)=QUARTER(now()) and p.project_name='"+pro+"' GROUP BY p.material_coding,p.work_type";
		List<Map<String,Object>> list=jdbc.queryForList(sql);
		List<Map<String,Object>> lis=jdbc.queryForList(sq);
		list=hb(list,lis);
		return list;

	}
	/**
	 * 本年度的统计
	 */
	public List<Map<String,Object>> year(){
		String pro=UserUtils.getUseroffice();
		String sql="SELECT p.code as code, p.name AS name, p.unit as unit,SUM(p.amount) as amount ,p.work_type as type FROM wms_pickdetailed p  where YEAR(p.create_date)=YEAR(NOW()) and p.project_name='"+pro+"' GROUP BY p.`code`,p.work_type";
		String sq="SELECT p.material_coding as code,SUM(p.quantities_received) as amount ,p.work_type as type FROM wms_receivings_notes p  where YEAR(p.create_date)=YEAR(NOW()) and p.project_name='"+pro+"' GROUP BY p.material_coding,p.work_type";
		List<Map<String,Object>> list=jdbc.queryForList(sql);
		List<Map<String,Object>> lis=jdbc.queryForList(sq);
		list=hb(list,lis);
		return list;

	}

	/**
	 * 出入库统计
	 * @return
	 */
	@RequestMapping(value="sum")
    public  String sum(Model model){
		model.addAttribute("list",day());

		model.addAttribute("list1",yue());

		model.addAttribute("list2",jidu());

		model.addAttribute("list3",year());

		return "modules/wms/sumList";
}
	/**
	 * 调用打印页面
	 */
	@RequestMapping(value = "dayin")
	public String dayin(HttpServletRequest request, String ids, Model model) throws Exception {
		//两个模版文件目录
		String templateFile = request.getSession().getServletContext().getRealPath("static/common/pdf/stenail/orderstenail.pdf");

		//要合并的pdf所在文件夹
		String folder = request.getSession().getServletContext().getRealPath("static/common/pdf/example/");

		PrintOrder printOrder = new PrintOrder();
		//用于存放需要合并的pdf文件名
		List<String> filelist = new ArrayList<String>();
		//多条数据
		String idArray[] = ids.split(",");
		Outbound outbound = null;
		List<PickDetailed> l = new ArrayList<PickDetailed>();

		for (String id : idArray) {
			 outbound = get(id);
			 outbound.setDycs(outbound.getDycs()+1);
			 outboundService.save(outbound);
			PickDetailed pickDetailed = new PickDetailed();
			pickDetailed.setOutbount(outbound.getId());
			List<PickDetailed> list =  pickDetailedService.findList(pickDetailed);
			l.addAll(list);
		}
		String pro=UserUtils.getUseroffice();
		Project project=projectService.findUniqueByProperty("name",pro);
		UpCustomers u=upCustomersService.findUniqueByProperty("project",project.getId());
		u=upCustomersService.get(u.getId());
		String ck="";
		for(TakeAddress t:u.getTakeAddressList()){
			if(t.getStore().contains("库")){
				ck=t.getStore();
			}
		}
		List<PickDetailed> pickDetailedList=new ArrayList<PickDetailed>();
		for(PickDetailed p:l){
			boolean bol=false;
			for(PickDetailed pi:pickDetailedList){
				if(p.getLocation().equals(pi.getLocation())&&p.getBach().equals(pi.getBach())&&p.getCode().equals(pi.getCode())){
				pi.setAmount((Integer.parseInt(pi.getAmount())+Integer.parseInt(p.getAmount()))+"");

				Goods g=new Goods();
				g.setCode(pi.getCode());
				g.setProject(UserUtils.getUseroffice());
				int i=p.getLs()+pi.getLs();
					Goods goods=goodsService.findList(g).get(0);
					int a=Integer.parseInt(goods.getTrayAmount());
					int aa=Integer.parseInt(goods.getProportion());
                if(i>=a*aa){
					pi.setTp(pi.getTp()+p.getTp()+1);
					pi.setLs((i-a*aa));
				}else{
					pi.setTp(pi.getTp()+p.getTp());
					pi.setLs(i);
				}
						bol=true;
				}
			}
			if(!bol){

				pickDetailedList.add(p);}

		}
		Double d=0.0;
		int amount=0;
		for(PickDetailed pp:pickDetailedList){
			amount+=Integer.parseInt(pp.getAmount());
			Goods g=new Goods();
			g.setCode(pp.getCode());
			g.setProject(UserUtils.getUseroffice());
			Goods goods=goodsService.findList(g).get(0);
			d+=Double.parseDouble(goods.getGrossWeight())*Double.parseDouble(pp.getAmount());
			int a=Integer.parseInt(goods.getProportion());
			pp.setLs(pp.getLs()/a);
		}
//			PickDetailed pickDetailed = new PickDetailed();
//			pickDetailed.setOutbount(outbound.getId());
			//如果子表大于10行
			int a = (pickDetailedList.size() / 5 );
		int group;
		if(pickDetailedList.size()%5==0){
			group=a ; //分组25   3
		}else{
			group=a+1;
		}

            for(int i=0;i<group;i++){
				List<PickDetailed> pickDetailedListNew = new ArrayList<PickDetailed>();
				//时间戳命名要合并的pdf并加入list
				String filewei = "outbound"+new Date().getTime() + ".pdf";
				//要合并的pdf目录
				String outFile = folder + "/"+filewei;
				File file = new File(outFile);
				if (!file.exists()) {
					try {
						file.createNewFile();
						System.out.println("创建成功!");
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
                if(i<group-1){
                    List<PickDetailed> pickDetailedList1 = (pickDetailedList.subList(i*5,(i+1)*5));
                    for (PickDetailed p:pickDetailedList1   ) {
                        pickDetailedListNew.add(p);
                    }
                    printOrder.updatePdfa(outbound,ck,d+"",amount, pickDetailedListNew, templateFile, file);
                    filelist.add(filewei);
                }else {
//                    System.out.println(pickDetailedList.subList(i*10,pickDetailedList.size()));
                    List<PickDetailed> pickDetailedList1 = (pickDetailedList.subList(i*5,pickDetailedList.size()));
                    for (PickDetailed p:pickDetailedList1   ) {
                        pickDetailedListNew.add(p);
                    }
                    printOrder.updatePdfa(outbound,ck,d+"",amount, pickDetailedListNew, templateFile, file);
                    filelist.add(filewei);
                }
            }


		//合并后pdf所在文件夹
		String outPdfFileqian = request.getSession().getServletContext().getRealPath("static/common/pdf/print/");
		//合并后pdf文件目录
		String outPdfFile = outPdfFileqian+"/mergepdf"+new Date().getTime() + ".pdf";
		//合并pdf方法
		printOrder.mergePdf(folder, outPdfFile,filelist);
//定时删除合并前的文件以及合并后的文件
		Timer timer = new Timer();//实例化Timer类
		timer.schedule(new TimerTask() {
			public void run() {
				try {
					FileUtil.deleteFile(outPdfFile);
					for (int i = 0; i < filelist.size(); i++){
						FileUtil.deleteFile(folder + File.separator + filelist.get(i));
						System.out.println("删除文件成功");}

				} catch (Exception e) {

				} finally {
					this.cancel();
				}

			}
		}, 50000);//五万毫秒 50秒
		//将合并后的pdf目录传到jsp供读取
		request.setAttribute("outPdfFile",outPdfFile);
		return "modules/wms/print/pdf";
	}
}